package com.evaluation.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.evaluation.common.Result;
import com.evaluation.entity.Teacher;
import com.evaluation.entity.Weixin;
import com.evaluation.entity.OaTeacher;
import com.evaluation.service.TeacherService;
import com.evaluation.service.WeixinService;
import com.evaluation.service.OaTeacherService;
import com.evaluation.util.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 教师管理控制器
 */
@RestController
@RequestMapping("/api/admin/teacher")
public class AdminTeacherController {

    @Autowired
    private TeacherService teacherService;
    
    @Autowired
    private WeixinService weixinService;
    
    @Autowired
    private OaTeacherService oaTeacherService;

    /**
     * 分页查询教师列表
     */
    @GetMapping("/list")
    public Result<Page<Teacher>> getTeacherList(@RequestParam(defaultValue = "1") Integer page,
                                 @RequestParam(defaultValue = "10") Integer size,
                                 @RequestParam(required = false) String jsxm,
                                 @RequestParam(required = false) String bmbh,
                                 @RequestParam(required = false) String jslx,
                                 @RequestParam(required = false) String gw) {
        try {
            QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();

            if (jsxm != null && !jsxm.trim().isEmpty()) {
                queryWrapper.like("JSXM", jsxm);
            }

            if (bmbh != null && !bmbh.trim().isEmpty()) {
                queryWrapper.eq("BMBH", bmbh);
            }

            if (jslx != null && !jslx.trim().isEmpty()) {
                queryWrapper.eq("JSLX", jslx);
            }

            if (gw != null && !gw.trim().isEmpty()) {
                queryWrapper.eq("GW", gw);
            }

            // 只查询有效教师
            queryWrapper.eq("JSZT", "0");
            queryWrapper.orderByAsc("JSBH");

            Page<Teacher> pageResult = teacherService.page(new Page<>(page, size), queryWrapper);

            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询教师列表失败");
        }
    }

    /**
     * 获取所有教师（用于下拉选择）
     */
    @GetMapping("/options")
    public Result<List<Teacher>> getTeacherOptions() {
        try {
            QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("JSZT", "0"); // 只查询有效教师
            queryWrapper.orderByAsc("JSXM");
            queryWrapper.select("JSBH", "JSXM", "BMBH", "BMMC");

            List<Teacher> teacherList = teacherService.list(queryWrapper);
            return Result.success(teacherList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取教师选项失败");
        }
    }

    /**
     * 根据ID查询教师详情
     */
    @GetMapping("/{jsbh}")
    public Result<Teacher> getTeacherById(@PathVariable Integer jsbh) {
        try {
            Teacher teacher = teacherService.getById(jsbh);
            if (teacher == null) {
                return Result.error("教师不存在");
            }
            return Result.success(teacher);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询教师详情失败");
        }
    }

    /**
     * 新增教师
     */
    @PostMapping
    public Result<String> addTeacher(@RequestBody Teacher teacher) {
        try {
            // 检查教师工号是否已存在
            if (teacher.getJsgh() != null && !teacher.getJsgh().trim().isEmpty()) {
                QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("JSGH", teacher.getJsgh());
                Teacher existingTeacher = teacherService.getOne(queryWrapper);
                if (existingTeacher != null) {
                    return Result.error("教师工号已存在");
                }
            }

            // 设置默认状态为有效
            teacher.setJszt("0");

            boolean result = teacherService.save(teacher);
            if (result) {
                return Result.success("添加成功");
            } else {
                return Result.error("添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("添加教师失败");
        }
    }

    /**
     * 更新教师
     */
    @PutMapping("/{jsbh}")
    public Result<String> updateTeacher(@PathVariable Integer jsbh, @RequestBody Teacher teacher) {
        try {
            teacher.setJsbh(jsbh);
            boolean result = teacherService.updateById(teacher);
            if (result) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新教师失败");
        }
    }

    /**
     * 删除教师（逻辑删除）
     */
    @DeleteMapping("/{jsbh}")
    public Result<String> deleteTeacher(@PathVariable Integer jsbh) {
        try {
            Teacher teacher = new Teacher();
            teacher.setJsbh(jsbh);
            teacher.setJszt("1"); // 设置为无效状态

            boolean result = teacherService.updateById(teacher);
            if (result) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除教师失败");
        }
    }

    /**
     * 批量导入教师
     */
    @PostMapping("/import")
    public Result<String> importTeachers(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.error("上传文件不能为空");
            }

            // 读取Excel文件
            List<Teacher> teacherList = ExcelUtil.readExcel(file, Teacher.class);
            
            if (teacherList.isEmpty()) {
                return Result.error("Excel文件中没有有效数据");
            }

            int successCount = 0;
            int errorCount = 0;

            for (Teacher teacher : teacherList) {
                try {
                    // 验证必填字段
                    if (teacher.getJsxm() == null || teacher.getJsxm().trim().isEmpty()) {
                        errorCount++;
                        continue;
                    }

                    // 检查教师是否已存在（根据姓名和工号）
                    QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("JSXM", teacher.getJsxm());
                    if (teacher.getJsgh() != null && !teacher.getJsgh().trim().isEmpty()) {
                        queryWrapper.or().eq("JSGH", teacher.getJsgh());
                    }

                    Teacher existingTeacher = teacherService.getOne(queryWrapper);
                    if (existingTeacher == null) {
                        // 设置默认值
                        if (teacher.getJslx() == null) teacher.setJslx("0");
                        if (teacher.getSfcp() == null) teacher.setSfcp("0");
                        if (teacher.getJszt() == null) teacher.setJszt("0");
                        if (teacher.getMm() == null) teacher.setMm("123456");
                        
                        teacherService.save(teacher);
                        successCount++;
                    } else {
                        // 更新现有教师信息
                        if (teacher.getBmbh() != null) existingTeacher.setBmbh(teacher.getBmbh());
                        if (teacher.getBmmc() != null) existingTeacher.setBmmc(teacher.getBmmc());
                        if (teacher.getGw() != null) existingTeacher.setGw(teacher.getGw());
                        if (teacher.getSjhm() != null) existingTeacher.setSjhm(teacher.getSjhm());
                        if (teacher.getJslx() != null) existingTeacher.setJslx(teacher.getJslx());
                        if (teacher.getSfcp() != null) existingTeacher.setSfcp(teacher.getSfcp());
                        
                        teacherService.updateById(existingTeacher);
                        successCount++;
                    }
                } catch (Exception e) {
                    errorCount++;
                    e.printStackTrace();
                }
            }

            return Result.success("导入完成，成功：" + successCount + "条，失败：" + errorCount + "条");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("导入教师失败：" + e.getMessage());
        }
    }

    /**
     * 重置教师密码
     */
    @PostMapping("/{jsbh}/reset-password")
    public Result<String> resetPassword(@PathVariable Integer jsbh) {
        try {
            Teacher teacher = new Teacher();
            teacher.setJsbh(jsbh);
            teacher.setMm("123456"); // 重置为默认密码

            boolean result = teacherService.updateById(teacher);
            if (result) {
                return Result.success("密码重置成功，新密码为：123456");
            } else {
                return Result.error("密码重置失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("密码重置失败");
        }
    }

    /**
     * 设置教师权限
     */
    @PostMapping("/{jsbh}/set-permission")
    public Result<String> setPermission(@PathVariable Integer jsbh, @RequestParam String qxlx) {
        try {
            Teacher teacher = new Teacher();
            teacher.setJsbh(jsbh);
            teacher.setQxlx(qxlx);

            boolean result = teacherService.updateById(teacher);
            if (result) {
                return Result.success("权限设置成功");
            } else {
                return Result.error("权限设置失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("权限设置失败");
        }
    }

    /**
     * 下载教师导入模板
     */
    @GetMapping("/template/download")
    public void downloadTemplate(HttpServletResponse response) {
        try {
            // 创建模板数据
            List<Map<String, Object>> templateData = new ArrayList<>();
            
            // 添加示例数据
            Map<String, Object> example1 = new HashMap<>();
            example1.put("教师编号", "10001");
            example1.put("教师工号", "JS001");
            example1.put("教师姓名", "张三");
            example1.put("部门编号", "11103");
            example1.put("部门名称", "网络信息部");
            example1.put("岗位", "20");
            example1.put("手机号码", "13800138001");
            example1.put("教师类型", "0");
            example1.put("是否参评", "0");
            example1.put("登录名", "zhangsan");
            example1.put("密码", "123456");
            example1.put("教师状态", "0");
            templateData.add(example1);

            Map<String, Object> example2 = new HashMap<>();
            example2.put("教师编号", "10002");
            example2.put("教师工号", "JS002");
            example2.put("教师姓名", "李四");
            example2.put("部门编号", "11105");
            example2.put("部门名称", "教学管理处");
            example2.put("岗位", "21");
            example2.put("手机号码", "13800138002");
            example2.put("教师类型", "1");
            example2.put("是否参评", "0");
            example2.put("登录名", "lisi");
            example2.put("密码", "123456");
            example2.put("教师状态", "0");
            templateData.add(example2);

            Map<String, Object> example3 = new HashMap<>();
            example3.put("教师编号", "10003");
            example3.put("教师工号", "JS003");
            example3.put("教师姓名", "王五");
            example3.put("部门编号", "11200");
            example3.put("部门名称", "计算机学院");
            example3.put("岗位", "24");
            example3.put("手机号码", "13800138003");
            example3.put("教师类型", "1");
            example3.put("是否参评", "0");
            example3.put("登录名", "wangwu");
            example3.put("密码", "123456");
            example3.put("教师状态", "0");
            templateData.add(example3);
            
            // 导出Excel
            ExcelUtil.exportExcel(response, "教师导入模板", templateData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 提取教师数据
     * 从T_TEACHER读取教师姓名，从T_WEIXIN读取企业微信和手机号码，从T_OA_TEACHER读取工号，更新到T_TEACHER表
     */
    @PostMapping("/extract-data")
    public Result<Map<String, Object>> extractTeacherData() {
        try {
            // 1. 从教师表读取所有教师姓名
            List<Teacher> teachers = teacherService.list(new QueryWrapper<Teacher>().eq("JSZT", "0"));
            
            int successCount = 0;
            int errorCount = 0;
            StringBuilder errorMessages = new StringBuilder();
            
            for (Teacher teacher : teachers) {
                try {
                    String jsxm = teacher.getJsxm();
                    if (jsxm == null || jsxm.trim().isEmpty()) {
                        errorCount++;
                        continue;
                    }
                    
                    boolean updated = false;
                    
                    // 2. 从企业微信表获取企业微信和手机号码
                    Weixin weixin = weixinService.getById(jsxm);
                    if (weixin != null) {
                        if (weixin.getQywx() != null && !weixin.getQywx().trim().isEmpty()) {
                            teacher.setQywx(weixin.getQywx());
                            updated = true;
                        }
                        if (weixin.getSjhm() != null && !weixin.getSjhm().trim().isEmpty()) {
                            teacher.setSjhm(weixin.getSjhm());
                            updated = true;
                        }
                    }
                    
                    // 3. 从OA教师表获取工号
                    OaTeacher oaTeacher = oaTeacherService.getById(jsxm);
                    if (oaTeacher != null && oaTeacher.getJsgh() != null && !oaTeacher.getJsgh().trim().isEmpty()) {
                        teacher.setJsgh(oaTeacher.getJsgh());
                        updated = true;
                    }
                    
                    // 4. 如果有数据更新，则保存到教师表
                    if (updated) {
                        teacherService.updateById(teacher);
                        successCount++;
                    }
                    
                } catch (Exception e) {
                    errorCount++;
                    errorMessages.append("教师 ").append(teacher.getJsxm()).append(" 数据提取失败: ").append(e.getMessage()).append("; ");
                    e.printStackTrace();
                }
            }
            
            String message = String.format("数据提取完成！成功更新 %d 位教师，失败 %d 位", successCount, errorCount);
            if (errorMessages.length() > 0) {
                message += "。错误详情：" + errorMessages.toString();
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("total", teachers.size());
            result.put("success", successCount);
            result.put("error", errorCount);
            result.put("message", message);
            
            return Result.success(result);
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("提取教师数据失败：" + e.getMessage());
        }
    }
}
